﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

public partial class Register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        bool isOK = CreateDiary(txtUsername.Text, txtPassword.Text, txtFirstName.Text, txtLastName.Text, txtEmail.Text);
        if (isOK)
        {
            Session["RegisterMessage"] = "Register Successfull";
            Response.Redirect("Login.aspx");
        }
        else
        {
            CustomValidator2.ErrorMessage = "Register Fail";
            CustomValidator2.IsValid = false;
        }
    }

    private bool CreateDiary(string username, string password, string firstName, string lassName, string email)
    {
        try
        {
            string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            string sql = "Insert Into [Diary] (Username, Password, Email, FirstName, LastName) Values (@1,@2,@3,@4,@5)";
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;
            cmd.Parameters.AddWithValue("@1", username);
            cmd.Parameters.AddWithValue("@2", password);
            cmd.Parameters.AddWithValue("@3", email);
            cmd.Parameters.AddWithValue("@4", firstName);
            cmd.Parameters.AddWithValue("@5", lassName);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}
